<!--
 * @Version: 1.0
 * @Date: 2021-04-08 20:24:32
 * @LastEditTime: 2021-11-26 14:13:59
 * @Description:
-->
<template>
  <el-card class="app-container">
    <div v-loading="loading">
      <div class="header_title_box">
        <h2 style="margin-right:50px">
          基本信息
        </h2>
      </div>
      <div class="from_box">
        <el-form ref="ruleForm" :model="ruleForm" inline :rules="rules" label-width="140px" class="dialog-form-expand2">
          <el-form-item label="售后类型" prop="type">
            <el-select v-model="ruleForm.type" :disabled="true" clearable placeholder="请选择售后类型">
              <el-option v-for="(item, index) in optionType" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.type===1" label="退款类型" prop="refund_type">
            <el-select v-model="ruleForm.refund_type" clearable placeholder="请选择退款类型">
              <el-option v-for="(item, index) in optionTypeReturn" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="售后原因" prop="sale_reason">
            <el-select v-model="ruleForm.sale_reason" placeholder="请选择售后原因" clearable>
              <el-option v-for="(item, index) in optionReason" :key="index" :value="item.value" :label="item.label" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.type===4" label="物流单号" prop="logistics_no">
            <el-input v-model="ruleForm.logistics_no" placeholder="请输入物流单号" />
          </el-form-item>
          <el-form-item v-if="ruleForm.type===3" label="补货类型" prop="replenish_type">
            <el-select v-model="ruleForm.replenish_type" placeholder="请选择补货类型" :disabled="true" clearable>
              <el-option v-for="(item, index) in optionTypeReplenish" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.type===4 || ruleForm.type===3" :label="`${ruleForm.type===2?'退货':(ruleForm.type===3 ? '补货': '召回')}物流`" prop="refund_logistics">
            <el-select v-model="ruleForm.refund_logistics" placeholder="请选择退货物流" clearable>
              <!-- <el-option key="ups" label="ups" :value="1" />
              <el-option key="usps" label="usps" :value="2" /> -->
              <el-option v-for="item in logisticsCompanyList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.type===2|| ruleForm.type===4" :label="`${ruleForm.type===2?'退货':'召回'}实体库`" prop="storage_id">
            <el-select v-model="ruleForm.storage_id" placeholder="请选择退货实体库" clearable @change="changeStorage">
              <el-option v-for="(item, index) in warehouseList" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.storage_id" :label="`仓库地址`" prop="storage_id">
            <span>{{ ruleForm.storage_address }}</span>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="ruleForm.remarks" placeholder="请填写备注" type="textarea" autosize />
          </el-form-item>
        </el-form>
        <!-- 配件信息 -->
        <div v-if="ruleForm.replenish_type === 2">
          <div class="header_title_box">
            <h2 style="margin-right:50px">
              配件信息
            </h2>
          </div>
          <div>
            <el-form ref="formData" :rules="model.rules" :model="model" class="dialog-form-expand3">
              <el-table :data="model.fieldsPrats" tooltip-effect="dark" style="width: 100%" border>
                <el-table-column align="center" label="缩略图" prop="url" />
                <el-table-column align="center" label="配件编码" prop="goods_code" />
                <el-table-column align="center" label="配件名称" prop="name" show-overflow-tooltip />
                <el-table-column v-if="ruleForm.type===3" align="center" :label="`补货数量`" width="130">
                  <template slot-scope="field">
                    <el-form-item :prop="'fields.' + field.$index + '.quantity_purchased'" :rules="model.rules.quantity_purchased">
                      <el-input-number v-model="field.row.quantity_purchased" size="mini" controls-position="right" :min="1" :precision="0" style="width:100px" />
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </div>
        <div v-if="ruleForm.type === 1 || ruleForm.type === 2 ||ruleForm.type === 4 || ruleForm.replenish_type === 1" class="header_title_box">
          <h2 style="margin-right:50px">
            订单商品明细信息
          </h2>
        </div>
        <!-- 商品信息 -->
        <div v-if="ruleForm.type === 1 || ruleForm.type === 2 ||ruleForm.type === 4 || ruleForm.replenish_type === 1" v-loading="loading">
          <el-form ref="formData" :rules="model.rules" :model="model" class="dialog-form-expand3">
            <el-table :data="model.fields" tooltip-effect="dark" style="width: 100%" border>
              <el-table-column align="center" label="缩略图" prop="url">
                <template slot-scope="scope">
                  <el-image style="width: 50px; height: 50px" fit="contain" :src="scope.row.goods_pic">
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline" />
                    </div>
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column align="center" label="系统sku" prop="goods_code" />
              <el-table-column align="center" label="商品名称" prop="name" show-overflow-tooltip />
              <el-table-column align="center" label="单价" prop="transaction_price_value">
                <template slot-scope="scope">
                  <app-price :price="scope.row.transaction_price_value" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="币别" prop="transaction_price_currencyid" />
              <el-table-column align="center" label="数量" prop="quantity_purchased" />
              <el-table-column align="center" label="金额(不含税)" prop="transaction_price_value_all">
                <template slot-scope="scope">
                  <app-price :price="scope.row.transaction_price_value_all" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="税费" prop="tax_amount_value">
                <template slot-scope="scope">
                  <app-price :price="scope.row.tax_amount_value" />
                </template>
              </el-table-column>
              <el-table-column v-if="ruleForm.type===2 || ruleForm.type===4" align="center" :label="`${ruleForm.type===2?'退货':'召回'}数量`" width="130">
                <template slot-scope="field">
                  <el-form-item :prop="'fields.' + field.$index + '.recall_num'" :rules="model.rules.recall_num">
                    <el-input-number v-model="field.row.recall_num" size="mini" controls-position="right" :min="1" :precision="0" :max="field.row.quantity_purchased" style="width:100px" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column v-if="ruleForm.type===3" align="center" :label="`补货数量`" width="130">
                <template slot-scope="field">
                  <el-form-item :prop="'fields.' + field.$index + '.recall_num'" :rules="model.rules.recall_num">
                    <el-input-number v-model="field.row.quantity_purchased" size="mini" controls-position="right" :min="1" :precision="0" style="width:100px" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column v-if="ruleForm.type===2 || ruleForm.type===1 || ruleForm.type===4" align="center" label="退款金额">
                <template slot-scope="field">
                  <el-form-item :prop="'fields.' + field.$index + '.fill_amount'" :rules="model.rules.fill_amount">
                    <el-input-number v-model="field.row.fill_amount" size="mini" placeholder="退款金额" autocomplete="off" :min="0" :precision="2" :max="field.row.transaction_price_value_all" :controls="false" />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
        <!-- 地址信息 -->
        <div v-if="ruleForm.type === 5|| ruleForm.type === 3">
          <div class="header_title_box">
            <h2>收货人信息 <span class="el-icon-edit-outline pointer blue" @click="disableAddress=!disableAddress" /></h2>
          </div>
          <el-form :model="formFieldsData" :rules="rules" label-width="140px" inline class="dialog-form-expand">
            <el-form-item label="买家姓名" :label-width="formLabelWidth" prop="address_name">
              <el-input v-model.trim="formFieldsData.address_name" :disabled="disableAddress" placeholder="请输入买家姓名" autocomplete="off" clearable style="width:177px" @input="inputChange" />
            </el-form-item>
            <!-- 买家的名字 -->
            <!-- <el-form-item label="买家名字" :label-width="formLabelWidth" prop="buyer_firstname">
              <el-input
                v-model.trim="formFieldsData.buyer_firstname"
                :disabled="disableAddress"
                placeholder="请输入买家名字"
                autocomplete="off"
                clearable
                style="width:177px"
                @input="inputChange"
              />
            </el-form-item> -->
            <!-- 买家的姓氏 buyer_lastname-->
            <!-- <el-form-item label="买家姓氏" :label-width="formLabelWidth" prop="buyer_lastname">
              <el-input
                v-model.trim="formFieldsData.buyer_lastname"
                :disabled="disableAddress"
                placeholder="请输入买家姓氏"
                autocomplete="off"
                clearable
                style="width:177px"
                @input="inputChange"
              />
            </el-form-item> -->
            <!-- 买家的邮箱 -->
            <el-form-item label="买家邮箱" :label-width="formLabelWidth" prop="address_email">
              <el-input v-model.trim="formFieldsData.address_email" :disabled="disableAddress" placeholder="请输入买家邮箱" autocomplete="off" clearable style="width:177px" @input="inputChange" />
            </el-form-item>
            <!-- 买家电话 -->
            <el-form-item label="买家电话" :label-width="formLabelWidth" prop="address_phone">
              <el-input v-model.trim="formFieldsData.address_phone" :disabled="disableAddress" placeholder="请输入买家电话" autocomplete="off" clearable style="width:177px" @input="inputChange" />
            </el-form-item>
            <!-- 买家的国家的代码 -->
            <el-form-item label="国家" :label-width="formLabelWidth" prop="address_country">
              <el-select v-model="formFieldsData.address_country" :disabled="disableAddress" placeholder="请选择店铺" filterable clearable style="width:177px">
                <el-option v-for="item in optionpCountry" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <!-- 买家的州/省（英文简写缩写） -->
            <el-form-item label="州/省" :label-width="formLabelWidth" prop="address_stateorprovince">
              <el-select v-model="formFieldsData.address_stateorprovince" :disabled="disableAddress" placeholder="请选择州/省" filterable clearable style="width:177px" @change="changeState">
                <el-option v-for="item in optionStates" :key="`${item.id}States`" :label="`${item.code}(${item.cname})`" :value="item.code" />
              </el-select>
            </el-form-item>
            <!-- 买家的城市 (英文全称) address_cityname-->
            <el-form-item label="城市" :label-width="formLabelWidth" prop="address_cityname">
              <el-select v-model="formFieldsData.address_cityname" :disabled="disableAddress" placeholder="请选择城市" filterable clearable style="width:177px" @change="changeCity">
                <el-option v-for="item in optionCity" :key="`${item.id}city`" :label="`${item.name}(${item.cname})(${item.code})`" :value="item.lower_name" />
              </el-select>
            </el-form-item>
            <!-- 买家的邮编 -->
            <el-form-item label="邮编" :label-width="formLabelWidth" prop="address_postalcode">
              <el-select v-model="formFieldsData.address_postalcode" :disabled="disableAddress" placeholder="请选择邮编" filterable clearable style="width:177px" @change="inputChange">
                <el-option v-for="item in optionPostalCode" :key="item.zip" :label="item.zip" :value="item.zip" />
              </el-select>
            </el-form-item>
            <!-- 买家的街道1 -->
            <el-form-item label="街道1" :label-width="formLabelWidth" prop="address_street1">
              <el-input v-model.trim="formFieldsData.address_street1" :disabled="disableAddress" placeholder="请输入街道1" autocomplete="off" clearable style="width:177px" @input="inputChange" />
            </el-form-item>
            <!-- 买家的街道2 -->
            <el-form-item label="街道2" :label-width="formLabelWidth" prop="address_street2">
              <el-input v-model.trim="formFieldsData.address_street2" :disabled="disableAddress" placeholder="请输入街道2" autocomplete="off" clearable style="width:177px" @input="inputChange" />
            </el-form-item>
            <!-- 买家的街道3 -->
            <el-form-item label="街道3" :label-width="formLabelWidth" prop="address_street3">
              <el-input v-model.trim="formFieldsData.address_street3" :disabled="disableAddress" placeholder="请输入街道3" autocomplete="off" clearable style="width:177px" @input="inputChange" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div>
        <div style="text-align: center; margin-top:50px">
          <el-button type="primary" :loading="isbtn" @click="submitForm('ruleForm')">保存</el-button>
          <el-button @click="handleCancelDown">取消</el-button>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script>
import {
  warehouseShop,
  statesList,
  cityList,
  cityPostalCode, lforwarderData
} from '@/utils/publicData'
export default {
  name: 'AfterSaleOrderEdit',
  data() {
    return {
      loading: false,
      tableData: [],
      optionpCountry: [{
        value: 'US',
        label: 'United States'
      }],
      logisticsCompanyList: [],
      optionStates: [],
      optionCity: [],
      optionPostalCode: [],
      disableAddress: false,
      formLabelWidth: '140px',
      formFieldsData: {
        address_name: '',
        buyer_firstname: '',
        buyer_lastname: '',
        address_email: '',
        address_phone: '',
        address_postalcode: '',
        address_country: '',
        address_country_name: '',
        address_stateorprovince: '',
        address_cityname: '',
        address_street1: '',
        address_street2: '',
        address_street3: ''
      },
      warehouseList: [],
      loadingTable: false,
      // 1-客户无理由退款退货 2-描述不符 3-包装问题 4-质量问题 5-物流问题
      optionReason: [
        {
          label: '客户无理由退款退货',
          value: 1
        },
        {
          label: '描述不符',
          value: 2
        },
        {
          label: '包装问题',
          value: 3
        },
        {
          label: '质量问题',
          value: 4
        },
        {
          label: '物流问题',
          value: 5
        },
        {
          label: '其他',
          value: 6
        }
      ],
      // 退款类型 1-部分退款 2-全部退款
      optionTypeReturn: [
        {
          label: '部分退款',
          value: 1
        },
        {
          label: '全部退款',
          value: 2
        }
      ],
      // 1-仅退款 2-退货退款 3-补货 4-召回 5-修改地址
      optionType: [
        {
          label: '仅退款',
          value: 1
        },
        {
          label: '退货退款',
          value: 2
        },
        {
          label: '补货',
          value: 3
        },
        {
          label: '召回',
          value: 4
        },
        {
          label: '修改地址',
          value: 5
        }
      ],
      // 补货类型
      optionTypeReplenish: [
        {
          label: '整件补货',
          value: 1
        },
        {
          label: '配件补货',
          value: 2
        }
      ],
      ruleForm: {
        type: '', // 类型
        sale_reason: '', // 售后原因
        remarks: '', // 备注
        refund_type: '', // 退款类型
        fill_amount: '', // 退款金额
        refund_amount: '', // 退款金额
        recall_num: 0, // 退款数量
        refund_logistics: '', // 退货物流
        storage_id: '', // 仓储id
        storage_address: '', // 仓储地址
        replenish_type: '', // // 补货类型 1-整件补货 2-配件补货
        logistics_no: ''
      },
      isbtn: false,
      rules: {
        logistics_no: [
          { required: true, message: '请输入物流单号', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择售后类型', trigger: 'blur' }
        ],
        sale_reason: [
          { required: true, message: '请选择售后原因', trigger: 'blur' }
        ],
        refund_type: [
          { required: true, message: '请选择退款类型', trigger: 'blur' }
        ],
        refund_logistics: [
          { required: true, message: '请选择物流类型', trigger: 'blur' }
        ],
        storage_id: [
          { required: true, message: '请选择仓库', trigger: 'blur' }
        ],
        address_name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }
        ],
        buyer_firstname: [{
          required: true,
          message: '请输入名',
          trigger: 'blur'
        }, {
          min: 1,
          max: 30,
          message: '长度在 1 到 20 个字符',
          trigger: 'blur'
        }],
        buyer_lastname: [{
          required: true,
          message: '请输入姓',
          trigger: 'blur'
        }, {
          min: 1,
          max: 30,
          message: '长度在 1 到 20 个字符',
          trigger: 'blur'
        }],
        address_email: [{
          required: false,
          message: '请输入邮箱地址',
          trigger: 'blur'
        }, {
          type: 'email',
          message: '请输入正确的邮箱地址',
          trigger: ['blur', 'change']
        }],
        address_phone: [{
          required: true,
          message: '请输入电话',
          trigger: 'blur'
        }],
        address_country: [{
          required: true,
          message: '请选择国家',
          trigger: 'blur'
        }],
        address_stateorprovince: [{
          required: true,
          message: '请选择州/省',
          trigger: 'blur'
        }],
        address_cityname: [{
          required: true,
          message: '请选择州/省',
          trigger: 'blur'
        }],
        address_postalcode: [{
          required: true,
          message: '请选择州/省',
          trigger: 'blur'
        }]
      },
      model: {
        rules: {
          recall_num: { required: true, message: '必填字段', trigger: 'blur' },
          fill_amount: { required: true, message: '必填字段', trigger: 'blur' },
          quantity_purchased: { required: true, message: '必填字段', trigger: 'blur' }
        },
        fields: [],
        fieldsPrats: []
      }
    }
  },
  created() {
    const vm = this
    statesList().then((data) => {
      this.optionStates = data
      if (this.$route.params.id) {
        this.disabled = true
        this.disableAddress = true
        this.disableProduct = true
        vm.orderInfo()
      }
    })
    this.getLogisticsCompany()
  },
  methods: {
    // 获取物流公司 数据字典
    getLogisticsCompany() {
      lforwarderData().then(res => {
        this.logisticsCompanyList = res
      })
    },
    orderInfo() {
      const vm = this
      vm.loading = true
      vm.$http.get(`/afterSaleOrders/addressInfo/${vm.$route.params.id}`).then((res) => {
        if (res.code === 10000) {
          const dataObj = res.data
          vm.ruleForm = dataObj
          if (vm.ruleForm.type === 5 || vm.ruleForm.type === 3) {
            vm.formFieldsData = res.data.address[0]
          }
          // 获取当前店铺绑定实体仓库
          warehouseShop(dataObj.shop_id).then(data => {
            this.warehouseList = data
            if (this.ruleForm.storage_id) {
              this.changeStorage(vm.ruleForm.storage_id)
            }
          })

          const product = dataObj.product
          if (vm.ruleForm.type === 2 || vm.ruleForm.type === 4) {
            vm.model.fields = dataObj.product_after_order.map((arr) => {
              arr.quantity_purchased = arr.number
              arr.name = arr.goods_name
              arr.recall_num = arr.number
              arr.fill_amount = vm.ruleForm.fill_amount
              arr.transaction_price_currencyid = arr.transaction_price_currencyid ? arr.transaction_price_currencyid : 'USD'
              arr.transaction_price_value_all = arr.transaction_price_value * arr.quantity_purchased
              return arr
            })
          } else {
            vm.model.fields = product.map((arr) => {
              arr.fill_amount = res.data.after_amount || 0
              arr.recall_num = res.data.recall_num
              arr.transaction_price_value_all = arr.transaction_price_value * arr.quantity_purchased
              return arr
            })
            if (vm.ruleForm.type === 1) {
              vm.model.fields = product.map((arr) => {
                arr.fill_amount = res.data.fill_amount || 0
                arr.recall_num = res.data.recall_num
                arr.transaction_price_value_all = arr.transaction_price_value * arr.quantity_purchased
                return arr
              })
            }
            if (vm.ruleForm.type === 3 && this.ruleForm.replenish_type === 1) {
              vm.model.fields = res.data.parts.map((arr) => {
                arr.transaction_price_value_all = arr.quantity_purchased * arr.transaction_price_value
                return arr
              })
            }
          }

          vm.model.fieldsPrats = dataObj.parts
          vm.loading = false
        } else {
          this.loading = false
        }
      })
    },
    // 修改省份
    changeState(value) {
      const address_stateorprovince = this.optionStates.filter((arr) => {
        return arr.code === value
      })
      cityList(address_stateorprovince[0].id).then(data => {
        this.optionCity = data
      })
      this.formFieldsData.address_postalcode = ''
      this.formFieldsData.address_cityname = ''
    },
    // 城市
    changeCity(value) {
      const obj = this.optionCity.filter((arr) => {
        return arr.lower_name === value
      })
      cityPostalCode(obj[0].id).then(data => {
        this.optionPostalCode = data.sort((a, b) => {
          return a.zip - b.zip
        })
      })
    },
    changeStorage(val) {
      this.warehouseList.map((arr) => {
        if (arr.value === val) {
          this.ruleForm.storage_address = arr.state + '/' + arr.city + '/' + arr.street
        }
      })
    },
    // 更新input不能输入的问题
    inputChange() {
      this.$forceUpdate()
    },
    // 关闭
    handleCancelDown() {
      this.$router.push({ path: '/afterSale/afterSaleOrder', query: { type: this.$route.query.type }})
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.ruleForm)
          delete data.created_at
          delete data.updated_at
          data.refund_amount = this.model.fields[0].fill_amount
          data.fill_amount = this.model.fields[0].fill_amount
          data.recall_num = this.model.fields[0].recall_num
          if (data.type === 3) {
            data.address = [this.formFieldsData]
            if (data.replenish_type === 2) {
              data.product = this.model.fieldsPrats.map((arr) => {
                return {
                  id: arr.id,
                  quantity_purchased: arr.quantity_purchased,
                  fill_amount: arr.fill_amount
                }
              })
            } else {
              data.product = this.model.fields.map((arr) => {
                return {
                  id: arr.id,
                  quantity_purchased: arr.quantity_purchased,
                  fill_amount: arr.fill_amount
                }
              })
            }
          }
          // 退货退款， 召回
          if (this.ruleForm.type === 2 || this.ruleForm.type === 4) {
            data.products = this.model.fields.map((arr) => {
              return {
                id: arr.id,
                return_num: arr.quantity_purchased,
                after_amount: arr.fill_amount
              }
            })
          }
          if (this.ruleForm.type === 1) {
            data.modify_amount = this.model.fields[0].fill_amount
          }
          this.$http.put(`/afterSaleOrder/${this.$route.params.id}`, data).then((res) => {
            if (res.code === 10000) {
              this.$message.success('售后申请编辑成功')
              this.handleCancelDown()
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
